﻿#include "ZQtDebugHandler.h"

#include <QtGlobal>
#include <QMutex>
#include <QMutexLocker>

ZFLIB_BEGIN_NAMESPACE

QSharedPointer<ZQtDebugHandler> ZQtDebugHandler::m_instance;
QMutex ZQtDebugHandler::m_instance_mutex;

static void messageHandleFunction(QtMsgType type, const QMessageLogContext &/*context*/, const QString &msg)
{
    QMetaObject::invokeMethod(ZQtDebugHandler::instance(), "message",
                              Q_ARG(QtMsgType, type),
                              Q_ARG(QString, msg));
}

ZQtDebugHandler *ZQtDebugHandler::instance()
{
    if (!m_instance)
    {
        QMutexLocker locker(&m_instance_mutex);
        if (!m_instance)
        {
            // 写成这样，是为了兼容低版本Qt
            m_instance = QSharedPointer<ZQtDebugHandler>(new ZQtDebugHandler);
        }
    }

    return m_instance.data();
}

void ZQtDebugHandler::destroyInstance()
{
    if (m_instance)
    {
        m_instance.clear();
    }
}

void ZQtDebugHandler::handle()
{
    qRegisterMetaType<QtMsgType>("QtMsgType");
    qInstallMessageHandler(messageHandleFunction);
}

void ZQtDebugHandler::release()
{

}

ZQtDebugHandler::ZQtDebugHandler(QObject *parent)
    :QObject(parent)
{
    handle();
}

ZQtDebugHandler::~ZQtDebugHandler()
{
    release();
}

ZFLIB_END_NAMESPACE
